package com.cslg.ac.demo.service.chat;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cslg.ac.demo.constant.ResponseCode;
import com.cslg.ac.demo.dao.chat.ChatDAO;
import com.cslg.ac.demo.dao.chat.po.ChatPO;
import com.cslg.ac.demo.entity.chat.Chat;
import com.cslg.ac.demo.exception.ChatNotFoundException;
import com.cslg.ac.demo.exception.PermissionForbiddenException;

@Service
public class ChatService {

	@Autowired
	private ChatDAO chatDAO;
	
	public int send(int fromId, int toId, String content)
	{
		//TODO 判断是否黑名单等
		ChatPO chatPO = new ChatPO();
		chatPO.setFromId(fromId);
		chatPO.setToId(toId);
		chatPO.setContent(content);
		chatDAO.insert(chatPO);
		return ResponseCode.REQUEST_SUCCESSED;
	}
	
	public Chat get(int userId, int id) throws ChatNotFoundException, PermissionForbiddenException
	{
		ChatPO chatPO = chatDAO.selectById(id);
		if(chatPO == null) {
			throw new ChatNotFoundException("聊天记录 [ " + id + "] 没有找到");
		}
		if(chatPO.getFromId() != userId && chatPO.getToId()  != userId) {
			throw new PermissionForbiddenException("用户 [" + userId + "] 查看聊天记录 [" + id + "] 的权限不够");
		}
		Chat chat = new Chat();
		BeanUtils.copyProperties(chatPO, chat);
		return chat;
	}
	
	public int[] get(int userId, int targetId, int offset, int num)
	{
		int[] ids = null;
		ids = chatDAO.select(userId, targetId, offset, num);
		return ids;
	}
	
	public int getLastInsertId()
	{
		return chatDAO.selectLastInsertId();
	}
	
}
